import pymysql


class DBUtil(object):
    __conn = None

    @classmethod
    def __get_conn(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", passwd="iHRM_student_2022",
                                         database="ihrm", charset="utf8")
        return cls.__conn

    @classmethod
    def __close_conn(cls):
        if cls.__conn:
            cls.__conn.close()
            cls.__conn = None

    @classmethod
    def get_one(cls, sql):
        cursor = None
        try:
            # 获取数据库连接对象
            conn = cls.__get_conn()
            # 获取游标
            cursor = conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as e:
            print(e)
            raise e
        finally:
            # 关闭游标
            if cursor:
                cursor.close()
            # 关闭数据库连接
            cls.__close_conn()
        return result

    @classmethod
    def _uid_db(cls, sql):
        conn = None
        cursor = None
        try:
            # 获取数据库连接对象
            conn = cls.__get_conn()
            # 获取游标
            cursor = conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 提交事务
            conn.commit()
        except Exception as e:
            print(e)
            # 回滚事务
            if conn:
                conn.rollback()
            # 抛出异常
            raise e
        finally:
            # 关闭游标
            if cursor:
                cursor.close()
            # 关闭数据库连接
            cls.__close_conn()
